package com.tib.filter;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.tib.utils.JwtUtil;
import com.tib.utils.ResponseResult;
import com.tib.em.StatusConstants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 该类查看token是否需要拦截或者放行
 * */
@WebFilter("/user/*")
public class Filter_2_JwtCheck implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //如果是登录或者退出，直接放行
        if(request.getRequestURI().contains("login") || request.getRequestURI().contains("logout") || request.getRequestURI().contains("register")){
            filterChain.doFilter(servletRequest,servletResponse);
            return ;
        }

        //获取token
        String token = request.getHeader("Admin-Token");
        HashMap<String, Object> checkToken = checkToken(token);
        //token验证失败
        if((Integer)checkToken.get("status")==StatusConstants.STATUS_DEFAULT_NO){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(
                                            ResponseResult.getResponseResult(
                                                    (Integer) checkToken.get("status"),
                                                    (String) checkToken.get("msg")
                                            )
                                      ));
            return;
        }
        //token验证成功放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    //检查签名是否有效
    private HashMap<String,Object> checkToken(String token){
        HashMap<String, Object> map = new HashMap<>();
        //解码token
        try{
            JwtUtil.verify(token);
            map.put("status", StatusConstants.STATUS_DEFAULT_YES);
            map.put("msg","请求成功！");
        }catch (SignatureVerificationException e){
            map.put("status", StatusConstants.STATUS_DEFAULT_NO);
            map.put("msg","签名无效！");
        }catch (TokenExpiredException e){
            map.put("status", StatusConstants.STATUS_DEFAULT_NO);
            map.put("msg","token过期！");
        }catch (AlgorithmMismatchException e){
            map.put("status", StatusConstants.STATUS_DEFAULT_NO);
            map.put("msg","token算法不一致！");
        }catch (Exception e){
            map.put("status",StatusConstants.STATUS_DEFAULT_NO);
            map.put("msg","token无效！");
        }
        return map;
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}
}
